package com.cat.dataStructure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/repeated-dna-sequences/
 * @create 2025/9/27 17:19
 * @since JDK17
 */

public class Solution84 {
    public List<String> findRepeatedDnaSequences(String s) {
        List<String> ans = new ArrayList<>();
        Map<Long, Integer> map = new HashMap<>();
        char[] arr = s.toCharArray();
        int n = arr.length, BASE = 499;
        if (n < 10) {
            return ans;
        }
        long hash = 0, p = 1;
        for (int i = 0; i < 9; i++) {
            hash = hash * BASE + arr[i];
            p *= BASE;
        }
        for (int l = 0, r = 9; r < n; l++, r++) {
            hash = hash * BASE + arr[r];
            map.merge(hash, 1, Integer::sum);
            if (map.get(hash) == 2) {
                ans.add(new String(s.substring(l, r + 1)));
            }
            hash -= arr[l] * p;
        }

        return ans;
    }
}
